package com.demo.supplier.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.supplier.dto.SupplierDto;
import com.demo.supplier.entity.SupplierInfo;
import com.demo.supplier.exception.BusinessException;
import com.demo.supplier.mapper.SupplierInfoMapper;
import com.demo.supplier.service.FileService;
import com.demo.supplier.service.SupplierInfoService;
import com.demo.supplier.vo.SupplierVo;
import com.demo.supplier.vo.SupplierDetailVo;
import com.demo.supplier.vo.FileInfoVo;
import com.demo.supplier.vo.FileUploadVo;
import com.demo.supplier.entity.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 供应商服务实现类
 * 
 * @author demo
 */
@Slf4j
@Service
public class SupplierInfoServiceImpl implements SupplierInfoService {

    @Autowired
    private SupplierInfoMapper supplierInfoMapper;

    @Autowired
    private FileService fileService;

    @Override
    public Page<SupplierVo> pageSuppliers(int current, int size, String keyword) {
        Page<SupplierInfo> page = new Page<>(current, size);
        
        LambdaQueryWrapper<SupplierInfo> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(keyword)) {
            wrapper.like(SupplierInfo::getSupplierCode, keyword)
                   .or()
                   .like(SupplierInfo::getSupplierName, keyword)
                   .or()
                   .like(SupplierInfo::getContactPerson, keyword);
        }
        wrapper.orderByDesc(SupplierInfo::getCreateTime);

        Page<SupplierInfo> supplierPage = supplierInfoMapper.selectPage(page, wrapper);
        
        // 转换为VO
        List<SupplierVo> supplierVos = supplierPage.getRecords().stream()
                .map(supplier -> BeanUtil.copyProperties(supplier, SupplierVo.class))
                .collect(Collectors.toList());

        Page<SupplierVo> result = new Page<>(current, size);
        result.setRecords(supplierVos);
        result.setTotal(supplierPage.getTotal());
        return result;
    }

    @Override
    public void createSupplier(SupplierDto supplierDto) {
        // 检查供应商编码是否存在
        if (getSupplierByCode(supplierDto.getSupplierCode()) != null) {
            throw new BusinessException("供应商编码已存在");
        }

        // 验证文件ID是否有效
        validateFileIds(supplierDto.getLogoFileId(), supplierDto.getLicenseFileId(), supplierDto.getCertificateFileId());

        SupplierInfo supplier = BeanUtil.copyProperties(supplierDto, SupplierInfo.class);
        
        // 设置默认值
        if (supplier.getStatus() == null) {
            supplier.setStatus(1);
        }

        supplierInfoMapper.insert(supplier);
    }

    @Override
    public void updateSupplier(SupplierDto supplierDto) {
        if (supplierDto.getId() == null) {
            throw new BusinessException("供应商ID不能为空");
        }

        SupplierInfo existSupplier = supplierInfoMapper.selectById(supplierDto.getId());
        if (existSupplier == null) {
            throw new BusinessException("供应商不存在");
        }

        // 检查供应商编码是否重复（排除自己）
        SupplierInfo checkSupplier = getSupplierByCode(supplierDto.getSupplierCode());
        if (checkSupplier != null && !checkSupplier.getId().equals(supplierDto.getId())) {
            throw new BusinessException("供应商编码已存在");
        }

        // 验证文件ID是否有效
        validateFileIds(supplierDto.getLogoFileId(), supplierDto.getLicenseFileId(), supplierDto.getCertificateFileId());

        // 处理文件更改，删除旧文件
        handleFileChanges(existSupplier, supplierDto);

        SupplierInfo supplier = BeanUtil.copyProperties(supplierDto, SupplierInfo.class);
        supplierInfoMapper.updateById(supplier);
    }

    @Override
    public void deleteSupplier(Long id) {
        SupplierInfo supplier = supplierInfoMapper.selectById(id);
        if (supplier == null) {
            throw new BusinessException("供应商不存在");
        }

        // 删除关联的Logo文件
        if (StrUtil.isNotBlank(supplier.getLogoUrl())) {
            try {
                String fileName = supplier.getLogoUrl().substring(supplier.getLogoUrl().lastIndexOf("/") + 1);
                fileService.deleteFile(fileName);
            } catch (Exception e) {
                log.warn("删除供应商Logo文件失败", e);
            }
        }

        supplierInfoMapper.deleteById(id);
    }

    /**
     * 根据供应商编码获取供应商
     */
    private SupplierInfo getSupplierByCode(String supplierCode) {
        LambdaQueryWrapper<SupplierInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SupplierInfo::getSupplierCode, supplierCode);
        return supplierInfoMapper.selectOne(wrapper);
    }

    @Override
    public SupplierDetailVo getSupplierWithFiles(Long supplierId) {
        SupplierInfo supplier = supplierInfoMapper.selectById(supplierId);
        if (supplier == null) {
            throw new BusinessException("供应商不存在");
        }

        SupplierDetailVo detailVo = BeanUtil.copyProperties(supplier, SupplierDetailVo.class);
        
        // 获取文件信息
        if (supplier.getLogoFileId() != null) {
            try {
                detailVo.setLogoFile(fileService.getFileInfo(supplier.getLogoFileId()));
            } catch (Exception e) {
                log.warn("获取Logo文件信息失败", e);
            }
        }
        
        if (supplier.getLicenseFileId() != null) {
            try {
                detailVo.setLicenseFile(fileService.getFileInfo(supplier.getLicenseFileId()));
            } catch (Exception e) {
                log.warn("获取营业执照文件信息失败", e);
            }
        }
        
        if (supplier.getCertificateFileId() != null) {
            try {
                detailVo.setCertificateFile(fileService.getFileInfo(supplier.getCertificateFileId()));
            } catch (Exception e) {
                log.warn("获取资质证书文件信息失败", e);
            }
        }
        
        return detailVo;
    }

    /**
     * 验证文件ID是否有效
     */
    private void validateFileIds(Long... fileIds) {
        for (Long fileId : fileIds) {
            if (fileId != null) {
                try {
                    fileService.getFileInfo(fileId);
                } catch (Exception e) {
                    throw new BusinessException("文件ID " + fileId + " 不存在或已被删除");
                }
            }
        }
    }

    /**
     * 处理文件更改，删除旧文件
     */
    private void handleFileChanges(SupplierInfo existSupplier, SupplierDto supplierDto) {
        // 处理Logo文件更改
        if (!Objects.equals(existSupplier.getLogoFileId(), supplierDto.getLogoFileId())) {
            if (existSupplier.getLogoFileId() != null) {
                try {
                    fileService.deleteFileById(existSupplier.getLogoFileId());
                } catch (Exception e) {
                    log.warn("删除旧Logo文件失败", e);
                }
            }
        }

        // 处理营业执照文件更改
        if (!Objects.equals(existSupplier.getLicenseFileId(), supplierDto.getLicenseFileId())) {
            if (existSupplier.getLicenseFileId() != null) {
                try {
                    fileService.deleteFileById(existSupplier.getLicenseFileId());
                } catch (Exception e) {
                    log.warn("删除旧营业执照文件失败", e);
                }
            }
        }

        // 处理资质证书文件更改
        if (!Objects.equals(existSupplier.getCertificateFileId(), supplierDto.getCertificateFileId())) {
            if (existSupplier.getCertificateFileId() != null) {
                try {
                    fileService.deleteFileById(existSupplier.getCertificateFileId());
                } catch (Exception e) {
                    log.warn("删除旧资质证书文件失败", e);
                }
            }
        }
    }
}